function loadShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert('编译着色器时发生错误: ' + gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return null;
    }
    
    return shader;
}

// 初始化着色器程序
function initShaderProgram(gl, vsSource, fsSource) {
    const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
    const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
    
    const shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertexShader);
    gl.attachShader(shaderProgram, fragmentShader);
    gl.linkProgram(shaderProgram);
    
    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert('无法初始化着色器程序: ' + gl.getProgramInfoLog(shaderProgram));
    return null;
    }
    
    return shaderProgram;
}
    

// 创建一个缓冲区，并填充三角形顶点的位置
function initBuffers(gl) {
    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    
    // 坐标(0,0)为场景的中心
    const positions = [
        -1.0,  0.0,
        0.0,  1.0,
        1.0, 0.0,
    ];
    
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
    
    return {
        position: positionBuffer,
    };
}

// 绘制场景
function drawScene(gl, programInfo, buffers) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    
    gl.useProgram(programInfo.program);
    
    gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
    gl.vertexAttribPointer(
        programInfo.attribLocations.vertexPosition,
        2,        // 每个迭代2个组件
        gl.FLOAT, // 数据是32位浮点数
        false,    // 不标准化
        0,        // 步长（0 = 自动）
        0         // 缓冲区中的偏移量
    );
    
    gl.drawArrays(gl.TRIANGLES, 0, 3);
}

function main() {
    const canvas = document.getElementById("glCanvas");
    const gl = canvas.getContext("webgl");
    
    if (!gl) {
        alert("无法初始化WebGL。您的浏览器或机器可能不支持它。");
        return;
    }
    
    // 设置清空画布的颜色为黑色，完全不透明
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    // 使用指定的清空颜色清空颜色缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);

    // 顶点着色器程序
    const vsSource = `
        attribute vec4 aVertexPosition;

        void main() {
        gl_Position = aVertexPosition;
        }
    `;

    // 片段着色器程序
    const fsSource = `
        void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `;

    const shaderProgram = initShaderProgram(gl, vsSource, fsSource);

    const programInfo = {
        program: shaderProgram,
        attribLocations: {
            vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
        },
    };

    const buffers = initBuffers(gl);

    drawScene(gl, programInfo, buffers);
}
    
window.onload = main;